package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Autowired
    private SetmealService setmealsService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ReportService reportService;

    /**
     * 会员数量统计
     *
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReportData() {
        Map<String, Object> dataMap = new HashMap<>();
        Calendar calendar = Calendar.getInstance();//获得日历对象，模拟时间
        calendar.add(Calendar.MONTH, -12);//计算时间
        List<String> months = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(time));
        }
        dataMap.put("months", months);//设定月份

        //根据月份查member数据
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        dataMap.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, dataMap);

    }

    /**
     * 套餐占比
     *
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        log.info("getSetmealReport");
        Map<String, Object> dataMap = new HashMap<>();//输出格式

        try {
            //setmealName
            List<String> setmealNames = new ArrayList<>();

            //findSetmealCount
            List<Map<String, Object>> SetmealCount = setmealsService.findSetmealCount();

            for (Map<String, Object> map : SetmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }

            //添加数据到map
            dataMap.put("setmealNames", setmealNames);
            dataMap.put("setmealCount", SetmealCount);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 运营数据统计
     *
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> dataMap = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, dataMap);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据excel
     *
     * @return
     */
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取运营数据
        Map<String, Object> data = reportService.getBusinessReportData();

        //读取excel模板
        InputStream path = getClass().getClassLoader().getResourceAsStream("templates/report_template.xlsx");
        //创建xssf
        XSSFWorkbook excel = new XSSFWorkbook(path);

        XSSFSheet sheet = excel.getSheetAt(0);
        sheet.getRow(2).getCell(5).setCellValue((String) data.get("reportDate"));
        sheet.getRow(4).getCell(5).setCellValue((Integer) data.get("todayNewMember"));
        sheet.getRow(4).getCell(7).setCellValue((Integer) data.get("totalMember"));
        sheet.getRow(5).getCell(5).setCellValue((Integer) data.get("thisWeekNewMember"));
        sheet.getRow(5).getCell(7).setCellValue((Integer) data.get("thisMonthNewMember"));
        sheet.getRow(7).getCell(5).setCellValue((Integer) data.get("todayOrderNumber"));
        sheet.getRow(7).getCell(7).setCellValue((Integer) data.get("todayVisitsNumber"));
        sheet.getRow(8).getCell(5).setCellValue((Integer) data.get("thisWeekOrderNumber"));
        sheet.getRow(8).getCell(7).setCellValue((Integer) data.get("thisWeekVisitsNumber"));
        sheet.getRow(9).getCell(5).setCellValue((Integer) data.get("thisMonthOrderNumber"));
        sheet.getRow(9).getCell(7).setCellValue((Integer) data.get("thisMonthVisitsNumber"));
        //热门套餐
//        Integer rownum = 12;
//        for (Map map : (List<Map>) data.get("hotSetmeal")) {
//            String name = (String) map.get("name");
//            Long setmeal_count = (Long) map.get("setmeal_count");
//            BigDecimal proportion = (BigDecimal) map.get("proportion");
//            rownum++;
//            sheet.getRow(rownum).getCell(4).setCellValue(name) ;
//            sheet.getRow(rownum).getCell(5).setCellValue(setmeal_count);
//            sheet.getRow(rownum).getCell(6).setCellValue(proportion.doubleValue());
//
//        }
        Integer rownum = 12;
        List<Map> hotSetmeal = (List<Map>) data.get("hotSetmeal");

// 检查 hotSetmeal 是否为空
        if (hotSetmeal == null || hotSetmeal.isEmpty()) {
            System.out.println("hotSetmeal is empty or null");
            return null;
        }

        for (Map map : hotSetmeal) {
            // 获取数据并处理空值
            String name = map.get("name") != null ? (String) map.get("name") : "";
            Long setmeal_count = map.get("setmeal_count") != null ? (Long) map.get("setmeal_count") : 0L;
            BigDecimal proportion = map.get("proportion") != null ? (BigDecimal) map.get("proportion") : BigDecimal.ZERO;

            // 获取行并处理空行
            Row row = sheet.getRow(rownum);
            if (row == null) {
                row = sheet.createRow(rownum); // 如果行为空，创建新行
            }

            // 设置单元格值
            row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellValue(name);
            row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellValue(setmeal_count);
            row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellValue(proportion.doubleValue());

            rownum++;
        }
        try {
            //输出到客户端浏览器
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=report.xlsx");
            excel.write(outputStream);
            log.info("下载成功");


            outputStream.close();
            excel.close();
            path.close();
            return null;
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
